package com.quectel.cms.controller.scheduling;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.scheduling.SchedulingCalendarConfigConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.scheduling.dto.SchedulingCalendarConfigBindingDto;
import com.quectel.core.module.scheduling.dto.SchedulingCalendarConfigDto;
import com.quectel.core.module.scheduling.service.SchedulingCalendarConfigBindingService;
import com.quectel.core.module.scheduling.service.SchedulingCalendarConfigService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@RestController
@RequestMapping("schedulingCalendarConfig")
@Tag(name = "SchedulingCalendarConfigController", description = "考勤日历相关api")
public class SchedulingCalendarConfigController extends BaseController {

    @DubboReference
    private SchedulingCalendarConfigService schedulingCalendarConfigService;
    @DubboReference
    private SchedulingCalendarConfigBindingService schedulingCalendarConfigBindingService;

    @GetMapping("queryAll")
    @Operation(summary = "获取考勤日历列表")
    public Response<List<SchedulingCalendarConfigDto>> queryAll() {
        //查询列表数据
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        request.put(LambdaUtil.getFieldName(SchedulingCalendarConfigDto::getStatus),SystemConstants.YES);

        int total = schedulingCalendarConfigService.queryTotal(request.getParams());

        List<SchedulingCalendarConfigDto> list = null;
        if (total > 0) {
            list = schedulingCalendarConfigService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        return Response.<List<SchedulingCalendarConfigDto>>ok().wrap(list);
    }


    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "schedulingCalendarConfig:list")
    @Operation(summary = "分页获取考勤日历列表")
    public Response<Page<SchedulingCalendarConfigDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = schedulingCalendarConfigService.queryTotal(request.getParams());

        List<SchedulingCalendarConfigDto> list = null;
        if (total > 0) {
            list = schedulingCalendarConfigService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SchedulingCalendarConfigDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SchedulingCalendarConfigDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "schedulingCalendarConfig:edit")
    @Operation(summary = "在编辑时根据id查询考勤日历详情")
    public Response<SchedulingCalendarConfigDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingCalendarConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingCalendarConfigDto schedulingCalendarConfigDto = schedulingCalendarConfigService.selectById(id);

        List<SchedulingCalendarConfigBindingDto> bindingDtos = schedulingCalendarConfigBindingService.selectListByConfigId(id);
        if (CollectionUtils.isNotEmpty(bindingDtos)){
            List<Date> holidays = bindingDtos.stream()
                    .filter(v -> v.getType().equals(SchedulingCalendarConfigConstants.DateType.HOLIDAY.getType()))
                    .map(SchedulingCalendarConfigBindingDto::getDate)
                    .collect(Collectors.toList());

            List<String> holidayList = new ArrayList<>();
            for (Date date : holidays){
                holidayList.add(DateUtil.format(date, DatePattern.NORM_DATE_PATTERN));
            }
            schedulingCalendarConfigDto.setHolidayDates(holidayList);

            List<Date> restdays = bindingDtos.stream()
                    .filter(v -> v.getType().equals(SchedulingCalendarConfigConstants.DateType.REST.getType()))
                    .map(SchedulingCalendarConfigBindingDto::getDate)
                    .collect(Collectors.toList());

            List<String> restdayList = new ArrayList<>();
            for (Date date : restdays){
                restdayList.add(DateUtil.format(date, DatePattern.NORM_DATE_PATTERN));
            }
            schedulingCalendarConfigDto.setRestDates(restdayList);
        }

        return Response.<SchedulingCalendarConfigDto>ok().wrap(schedulingCalendarConfigDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "schedulingCalendarConfig:info")
    @Operation(summary = "根据id查询考勤日历的详情")
    public Response<SchedulingCalendarConfigDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingCalendarConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingCalendarConfigDto schedulingCalendarConfigDto = schedulingCalendarConfigService.selectById(id);

        return Response.<SchedulingCalendarConfigDto>ok().wrap(schedulingCalendarConfigDto);
    }

    /**
     * 保存
     *
     * @param schedulingCalendarConfigDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "schedulingCalendarConfig:edit")
    @Operation(summary = "新增考勤日历")
    public Response<Object> save(@RequestBody @Validated SchedulingCalendarConfigDto schedulingCalendarConfigDto) {

        //填充基础数据
        fillSaveCommonData(schedulingCalendarConfigDto);

        schedulingCalendarConfigService.saveOrUpdate(schedulingCalendarConfigDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param schedulingCalendarConfigDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "schedulingCalendarConfig:edit")
    @Operation(summary = "根据id修改考勤日历")
    public Response<Object> update(@RequestBody  @Validated SchedulingCalendarConfigDto schedulingCalendarConfigDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(schedulingCalendarConfigDto.getId()));
        if (schedulingCalendarConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(schedulingCalendarConfigDto);

        schedulingCalendarConfigService.saveOrUpdate(schedulingCalendarConfigDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "schedulingCalendarConfig:delete")
    @Operation(summary = "根据多条记录id批量删除考勤日历")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (schedulingCalendarConfigService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        schedulingCalendarConfigService.deleteBatch(ids);

        return Response.ok();
    }
}
